package cn.edu.xmu.orderpayment.payment.util.paypattern;

import cn.edu.xmu.orderpayment.payment.microservice.returnobj.WeChatReturnObject;
import cn.edu.xmu.orderpayment.payment.microservice.service.WeChatPayService;
import cn.edu.xmu.orderpayment.payment.microservice.wechatpayvo.*;
import cn.edu.xmu.orderpayment.payment.mq.listener.PayCheckListener;
import cn.edu.xmu.orderpayment.payment.util.baseobject.*;
import cn.edu.xmu.orderpayment.payment.util.config.payconfigs.WeChatPayConfig;
import cn.edu.xmu.privilegegateway.annotation.util.JacksonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.xmu.orderpayment.payment.model.bo.Amount;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Yujie Lin
 * @date 2021/12/12 16:48
 */
@Component
public class WeChatPaymentPattern implements  BasePaymentPattern{

    private final Logger logger = LoggerFactory.getLogger(WeChatPaymentPattern.class);


    @Autowired
    private WeChatPayConfig weChatPayConfig;

    @Autowired
    private WeChatPayService weChatPayService;

    @Override
    public DoPayInfo pay(String outTradeNo, Amount amount, String description) {
        WeChatPayTransactionVo weChatPayTransactionVo = new WeChatPayTransactionVo();

            weChatPayTransactionVo.setAppid(weChatPayConfig.getAppId());
            weChatPayTransactionVo.setMchid(weChatPayConfig.getMchId());
            weChatPayTransactionVo.setDescription(description);
            weChatPayTransactionVo.setTimeExpire(LocalDateTime.now());
            weChatPayTransactionVo.setOutTradeNo(outTradeNo);
            weChatPayTransactionVo.setAmount(new WeChatPayTransactionVo.TransactionAmountVo(Math.toIntExact(amount.getTotal()) ,amount.getCurrency()));
            weChatPayTransactionVo.setPayer(new WeChatPayTransactionVo.PayerVo(weChatPayConfig.getOpenId()));
            weChatPayTransactionVo.setNotifyUrl(weChatPayConfig.getPayNotifyUrl());


        String s= JacksonUtil.toJson(weChatPayTransactionVo);
        logger.info(s);

        WeChatReturnObject<WeChatPayPrepayRetVo> weChatReturnObject= weChatPayService.createTransaction(weChatPayTransactionVo);
        return weChatReturnObject.getData().createDoPayInfo();
    }

    @Override
    public PaymentInfo getPayment(String outTradeNo) {
        WeChatReturnObject<WeChatPayTransactionRetVo> weChatReturnObject= weChatPayService.getTransaction(outTradeNo);

        if(weChatReturnObject!=null&&weChatReturnObject.getData()!=null){
            logger.info(weChatReturnObject.getData().toString());
            return weChatReturnObject.getData().createPaymentInfo();
        }

        return null;
    }

    @Override
    public void closePayment(String outTradeNo) {
        weChatPayService.closeTransaction(outTradeNo);
    }

    @Override
    public void refund(Amount amount, String outTradeNo, String outRefundNo, String reason) {
        WeChatPayRefundVo weChatPayRefundVo=new WeChatPayRefundVo(weChatPayConfig,amount, outTradeNo, outRefundNo,reason);
        weChatPayService.createRefund(weChatPayRefundVo);
    }

    @Override
    public RefundInfo getRefund(String outTradeNo, String outRefundNo) {
        WeChatReturnObject<WeChatPayRefundRetVo> weChatReturnObject=weChatPayService.getRefund(outRefundNo);
        if(weChatReturnObject!=null&&weChatReturnObject.getData()!=null)
            return weChatReturnObject.getData().createRefundInfo();
        return null;
    }

    @Override
    public BillDownloadInfo getBillDownloadUrl(LocalDate billDate) {
        return new BillDownloadInfo(null,null,"../transaction/微信支付账单(20211011-20211211).csv");
    }

    @Override
    public List<Transaction> getTransactionsFromCSV(String downloadUrl) {
        List<Transaction> transactions = new ArrayList<>();
        try {
            File file = new File(downloadUrl);
            if (file.exists())  {
                //微信支付账单下载后发现是UTF-8编码
                InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line = null;
                String regex =  "\\d*[.]\\d*";
                Pattern p = Pattern.compile(regex);
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                while ((line = reader.readLine()) != null) {
                    String [] item = line.split(",");
                    if(item.length==11) {
                        if(item[0].equals("交易时间")){
                            continue;
                        }
                        LocalDateTime transactionTime = LocalDateTime.parse(item[0],dateTimeFormatter);
                        Long amount = Long.valueOf(0);
                        Matcher m = p.matcher(item[5]);
                        while (m.find()) {
                            if (!"".equals(m.group())) {
                                amount = Long.valueOf((long) (100 * Double.valueOf(m.group())));
                            }
                        }
                        Transaction.TransactionType transactionType = Transaction.TransactionType.REFUND;
                        String tradeSn = item[8].trim();
                        String requestSn = item[9].trim();
                        if(item[4].equals("收入")){
                            transactionType = Transaction.TransactionType.PAY;
                        }
                        Transaction transaction = new Transaction(tradeSn,requestSn,transactionTime, transactionType,amount);
                        transactions.add(transaction);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return transactions;
    }
}
